from flask import Blueprint, request, render_template, redirect, url_for
from flask_wtf import FlaskForm
from wtforms.validators import DataRequired, Length
from wtforms.fields import *
from util.dbutil import Base, db
from util.comutil import set_password, check_password
from sqlalchemy import Column, Integer, String, Text, DateTime
import datetime

user = Blueprint('user', __name__, url_prefix='/user')

# bootstrap-flask用户登录对象
class LoginForm(FlaskForm):
    username = StringField('用户名', validators=[DataRequired(), Length(1, 20)])
    password = PasswordField('密码', validators=[DataRequired(), Length(8, 150)])
    submit = SubmitField(label='登录')

# bootstrap-flask用户注册对象
class RegisterForm(FlaskForm):
    username = StringField('用户名', validators=[DataRequired(), Length(1, 20)])
    password = PasswordField('密码', validators=[DataRequired(), Length(8, 150)])
    submit = SubmitField(label='注册')

# 用户表对象
class User(Base):
    __tablename__ = 'user'  # 数据库表名称， 必须写
    # 主键
    id = Column(Integer, primary_key=True)  
    # 用户名
    username = Column(String(32), index=True, nullable=False)  
    # 密码
    password = Column(String(256), unique=True, nullable=False)
    # 创建时间datetime.datetime.now不能加括号，加了括号，以后永远是当前时间
    createtime = Column(DateTime, default=datetime.datetime.now)
    # 更新时间
    updatetime = Column(DateTime, default=datetime.datetime.now)
    # 备注
    extra = Column(Text, nullable=True)


# 用户登录提交
@user.route('/login/submit', methods=['POST'])
def loginSubmit():
    loginInfo = request.form.to_dict()
    username = loginInfo['username']
    password = loginInfo['password']
    user = db.query(User).filter(User.username == username).first()
    if(user == None):
        # 当前用户不存在,跳转到注册页
        return redirect(url_for('user.registerIndex'), code=302)
    elif(check_password(password=password, pwhash=user.password)):
        # 登录成功跳转到导航页
        return redirect('/back/index')
    else:
        # 登录失败跳到登录页面
        return redirect(url_for('user.loginIndex'), code=302)

# 用户注册提交
@user.route('/register/submit', methods=['POST'])
def registerSubmit():
    # 注册成功后进入登录页
    registerInfo = request.form.to_dict()
    username = registerInfo['username']
    passwd = registerInfo['password']
    password = set_password(password=passwd)
    db.add(User(username=username, password=password))
    db.commit()
    return redirect(url_for('user.loginIndex'), code=302)

# 查询所有用户信息
@user.route('/list')
def userList():
    users = db.query(User).all()
    db.commit()
    titles = [('id', '#'), ('username', '用户名'), ('createtime', '创建时间')]
    data = []
    for user in users:
        data.append({'id': user.id, 'username': user.username, 'createtime': user.createtime})
    return render_template('user/index.html', users=users, titles=titles, User=User, data=data)